import React from "react";
import {Form, Input} from "antd";
import {LongButton} from "./index";
import {useAuth} from "context/auth-context";
import {useAsync} from "hooks/useAsync";

export default ({onError}: { onError: (error: Error) => void }) => {
  const {register} = useAuth();
  const {run, isLoading} = useAsync(undefined, {throwOnError: true});

  const handleSubmit = async ({pwd, ...values}: { username: string; password: string; pwd: string; }) => {
    try {
      await run(register(values))
    } catch (e) {
      onError(e)
    }
  };

  return (
    <Form onFinish={handleSubmit}>
      <Form.Item name={"username"} rules={[{required: true, message: "请输入用户名"}]}>
        <Input placeholder={"用户名"} type="text" id={"username"}/>
      </Form.Item>
      <Form.Item name={"password"} rules={[{required: true, message: "请输入密码"}]}>
        <Input placeholder={"密码"} type="password" id={"password"}/>
      </Form.Item>
      <Form.Item name={"pwd"} rules={[{required: true, message: "请确认密码"}]}>
        <Input placeholder={"确认密码"} type="password" id={"pwd"}/>
      </Form.Item>
      <Form.Item>
        <LongButton htmlType={"submit"} type={"primary"} loading={isLoading}>注册</LongButton>
      </Form.Item>
    </Form>
  )
};
